#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

static MyFile *BuyFile(int fd, int flag)
{
    MyFile* cmp = (MyFile *)melloc(sizeof(MyFile));
    cmp->flag = flag;
    cmp->fileno = fd;
    cmp->bufferlen = 0;
    //行？文件？满？
    //默认行刷新
    cmp->flush_method-> = LINE_FULSH;
    memset(cmp->buffer,0,sizeof(cmp->buffer));
    return cmp;
}

MyFile *Myopen(const char* filename, const char* mode)
{
    int flag = 0;
    int fd = 0;
    if(strcmp(mode,"w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(filename, flag, 0666);
        if (fd == -1) 
        {
            perror("open_w");
        }
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(filename, flag, 0666);
        if (fd == -1) 
        {
            perror("open_a");
        }
    }
    else if(strcmp(mode,"r") == 0)
    {
        flag = O_RDONLY;
        fd = open(filename, flag);
        if (fd == -1) 
        {
            perror("open_r");
        }
    }
    else{
        ////
    }
    return BuyFile(fd, flag);
}

size_t  Mywrite(const void *ptr, size_t size, size_t nmemb, MyFile *stream)
{
    //size_t bytes = write(stream->fd,stream->buffer,stream->bufferlen);
    //if (fd == -1)
    //{
    //    perror("Mywrite");
    //}
    //return bytes;
    //缓冲区不足
    if(Max-(stream->bufferlen) < size * nmemb)
    {
        Myflush(stream);
    }
    memcpy(stream->outbuffer + stream->bufflen, ptr, size * nmemb);
    stream->bufferlen += size * nmemb;
    //行刷新 
    if ((stream->flush_method & LINE_FULSH) && stream->outbuffer[stream->bufferlen-1] == '\n')
    {
        Myflush(stream);
    }
    return size * nmemb;
}


int Myclose(MyFile *stream)
{
    Myflush(stream);
    int n = close(stream->fileno);
    if(n == -1)
    {
        perror("Myclose");
    }
    return n;
}

int Myflush(MyFile *stream)
{
    size_t bytes = write(stream->fileno, stream->outbuffer, stream->bufferlen);
    if (bytes == -1)
        perror("Myflush");
    stream->bufferlen = 0;
    return size_t;
}
